package com.feicheng.controller.main.admin.system;


import com.alibaba.fastjson.JSONObject;
import com.feicheng.common.result.ResultInfo;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RestController("/main/admin/system/upload")
@RequestMapping("/main/admin/system/upload")
public class FileUploadController {

    @GetMapping("/test")
    public ResultInfo testUpload() {
        try {
            String xy = System.getProperty("user.dir");
            System.out.println(xy);

            String path = ResourceUtils.getURL("classpath:").getPath();
            System.out.println(path);
            return ResultInfo.success(path);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultInfo.fail("cuole");

    }

    @PostMapping("/file")
    public ResultInfo uploadFile(MultipartFile[] files) {
        JSONObject result = new JSONObject();
        String currentPath = new File("/").getAbsolutePath();
        File certDir = new File(currentPath + File.separator + "cert" + File.separator);

        if (!certDir.exists()) {
            certDir.mkdirs();
        }

        try {
            if (null != files && files.length > 0) {
                for (MultipartFile file : files) {
                    String fileName = certDir.getAbsolutePath()+File.separator+System.currentTimeMillis()+file.getOriginalFilename();
                    File certFile = new File(fileName);
                    file.transferTo(certFile);
                    result.put(file.getOriginalFilename(), certFile.getAbsolutePath());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultInfo.success(result);
    }
}
